#!/bin/bash

HZRCB_HOME=/home/hzrcb/hzrcb
PID_HOME=$HZRCB_HOME/pids
LOG_HOME=$HZRCB_HOME/logs

if [ ! -d "$PID_HOME" ]; then
    mkdir $PID_HOME
    echo "create pid directory: $PID_HOME"
fi

if [ ! -d "$LOG_HOME" ]; then
    mkdir $LOG_HOME
    echo "create log directory: $PID_HOME"
fi

start() {
    name=$1
    pidFile=$PID_HOME/$name.pid
    workingDir=$PWD

    echo "try to start $name ..."

    if [ -f $pidFile ]; then
        echo "$name is still running, try to close it."
        kill -15 `cat $pidFile`
        rm $pidFile
    fi

    pid=""
    if [ "$name" = "web" ]; then
        cd $HZRCB_HOME/web
        nohup npm run start >> $LOG_HOME/$name.log 2>&1 &
        pid=$!
    else
        shift
        opts=$@
        if [ "$opts" = "" ]; then
            opts=""
        fi
        mainOpts=("-Xmx" "-Dspring.profiles.active=prod" "-Dspring.config.location")
        mainOptValues=("512M" ""  "=classpath:/,$HZRCB_HOME/configs/common/,$HZRCB_HOME/configs/$name/")
        for ((idx=0; idx<${#mainOpts[@]}; idx++)); do
            opt=${mainOpts[$idx]}
            if [[ ! $opts =~ $opt ]]; then
                # if opts does not contains this option, append it.
                opts="$opts $opt${mainOptValues[$idx]}"
            fi
        done

        jarFile=$HZRCB_HOME/jars/$name-1.0-SNAPSHOT.jar
        if [ ! -f "$jarFile" ]; then
            echo "not such app: $name"
        else
            echo "java $opts -jar $jarFile"
            nohup java $opts -jar $jarFile > $LOG_HOME/$name.log 2>&1 & # /dev/null 2>&1 &
            pid=$!
        fi
    fi

    echo "$pid" > $pidFile
    echo "$name is running at pid: $pid"
    cd $workingDir
}

stop() {
    name=$1
    pidFile=$PID_HOME/$name.pid

    if [ -f $pidFile ]; then
        kill -15 `cat $pidFile`
        rm $pidFile
        echo "$name is stoped."
    fi
}

apps=("base-registration" "base-gateway" "api-privilege" "api-login" "api-system" "api-sms" "api-random" "web")
appsLength=${#apps[@]}

startAll() {
    for ((i=0; i<$appsLength; i++)); do
        app=${apps[$i]}
        start $app
        echo ""
        if [ "$app" = "" ]; then
            sleep 5
        else
            sleep 1
        fi
    done
}

stopAll() {
    for ((i=${#apps[@]}-1; i>=0; i--)); do
        app=${apps[$i]}
        stop $app
        sleep 1
    done
}

command=$1
shift
commandOpts=$@
targetApp=$1

echo $command $commandOpts
echo ""

case $command in
    start)
        if [ "$targetApp" = "" ]; then
            startAll
        else
            start $commandOpts
        fi
        ;;
    stop)
        if [ "$targetApp" = "" ]; then
            stopAll
        else
            stop $commandOpts
        fi
        ;;
    restart)
        if [ "$targetApp" = "" ]; then
            stopAll
            startAll
        else
            stop $commandOpts
            start $commandOpts
        fi
        ;;
esac

exit 0

